package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrderDto;
import com.itheima.reggie.entity.OrderDetail;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.OrderService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @author：shaodan.wang
 * @date: 2022-05-07
 */

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderDetailService orderDetailService;



    @PostMapping("/submit")
    public R<String> submit( @RequestBody Orders orders){
        orderService.submit(orders);
        return R.success("订单提交成功");

    }

    @GetMapping("/userPage")
    public R<Page> orderPage(@RequestParam int page, @RequestParam int pageSize){

        Page pageInfo = new Page(page,pageSize);

        //获得当前用户id
        Long userId = BaseContext.getCurenId();

        //查询当前用户的订单数据
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Orders::getUserId,userId);
        List<Orders> orderList = orderService.list(wrapper);

        //存放各个订单和订单细节数据
        List<OrderDto> list = new ArrayList<>();

        for(int i = 0; i< orderList.size(); i++){

            OrderDto orderDto = new OrderDto();
            //将订单对应的属性复制到orderDto中
            BeanUtils.copyProperties(orderList.get(i),orderDto);
            //获得订单Id
            Long id = orderList.get(i).getId();

            //查询对应的订单细节
            LambdaQueryWrapper<OrderDetail> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(OrderDetail::getOrderId,id);

            //获得该订单的所有订单细节
            List<OrderDetail> list1 = orderDetailService.list(wrapper1);

             //将订单细节存入orderDto中
            orderDto.setOrderDetails(list1);

            //orderDto装配完毕，将其存入其中
            list.add(orderDto);
        }

        //将获得到的每个订单存入进去
        pageInfo.setRecords(list);

        return R.success(pageInfo);
    }
}
